package com.soriya.nestlive.component

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.AlertDialog
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PowerSettingsNew
import androidx.compose.material.icons.outlined.Image
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.soriya.nestlive.constant.UIValue
import com.soriya.nestlive.im.MessageType
import com.soriya.nestlive.model.Live
import com.soriya.nestlive.model.LiveChat
import com.soriya.nestlive.viewmodel.LiveChatModel
import kotlinx.coroutines.launch

@Composable
fun LiveTitle(
    modifier: Modifier = Modifier,
    onExit: () -> Unit
) = Row(
    verticalAlignment = Alignment.CenterVertically,
    modifier = modifier
) {
    var openExitDialog by remember {
        mutableStateOf(false)
    }

    val coroutineScope = rememberCoroutineScope()

    CompositionLocalProvider(LocalContentColor provides Color.White) {
        Row(
            modifier = Modifier
                .clip(RoundedCornerShape(50))
                .background(Color.Black.copy(0.45F))
                .padding(6.dp)
                .height(36.dp)
        ) {
            CustomImage(
                url = "https://gimg0.baidu.com/gimg/src=https%3A%2F%2Fgameplus-platform.cdn.bcebos.com%2Fgameplus-platform%2Fupload%2Ffile%2Fimg%2F48ce8034a7378ce56a6ad5fdbfd0daac%2F48ce8034a7378ce56a6ad5fdbfd0daac.png&app=2000&size=f180,180&n=0&g=0n&q=85&fmt=jpeg?sec=0&t=c3aca64da2fb743cc44361dacf371198",
                contentDescription = "Avatar",
                shape = CircleShape,
                modifier = Modifier.size(36.dp)
            )

            Column(
                verticalArrangement = Arrangement.SpaceBetween,
                modifier = Modifier
                    .fillMaxHeight()
                    .padding(start = 10.dp, end = 20.dp)
            ) {
                SmallText(text = "SoRiya")
                SmallerText(text = "1人")
            }
        }

        Row(
            modifier = Modifier
                .weight(1F)
        ) {

        }

        IconButton(onClick = {
            openExitDialog = true
        }) {
            Icon(
                imageVector = Icons.Default.PowerSettingsNew,
                contentDescription = "Exit",
                modifier = Modifier
                    .size(36.dp)
            )
        }
    }

    takeIf {
        openExitDialog
    }?.let {
        AlertDialog(
            onDismissRequest = {
                openExitDialog = false
            },
            confirmButton = {
                TextButton(onClick = {
                    openExitDialog = false
                    onExit()
                }) {
                    Text(text = "确认")
                }
            },
            dismissButton = {
                TextButton(onClick = {
                    openExitDialog = false
                }) {
                    Text(text = "取消")
                }
            },
            text = {
                MediumText(text = "确认退出直播？")
            },
            backgroundColor = MaterialTheme.colors.background,
            modifier = Modifier.background(Color.Black)
        )
    }
}

@Composable
fun CameraLiveTitleEdit(
    modifier: Modifier = Modifier
) = Row(
    verticalAlignment = Alignment.CenterVertically,
    modifier = modifier
//                    .fillMaxWidth()
        .clip(RoundedCornerShape(UIValue.SMALL_RADIUS))
        .background(Color.Black.copy(alpha = 0.6F))
        .padding(16.dp)
) {
    CompositionLocalProvider(LocalContentColor provides Color.White) {
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier.size(80.dp)
        ) {
            Icon(
                imageVector = Icons.Outlined.Image,
                contentDescription = "Live Cover",
                modifier = Modifier.size(40.dp)
            )
        }

        Spacer(
            modifier = Modifier
                .width(1.dp)
                .height(80.dp)
                .background(
                    LocalContentColor.current.copy(alpha = 0.4F)
                )
        )

        TextField(
            value = "",
            onValueChange = {},
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.Transparent,
                unfocusedIndicatorColor = Color.Transparent,
                focusedIndicatorColor = Color.Transparent
            ),
            placeholder = {
                MediumText(text = "给直播写个标题吧~", color = Color.White)
            }
        )
    }
}

@Composable
fun LiveOptionButton(
    icon: ImageVector,
    contentDescription: String,
    onclick: () -> Unit
) {
    CompositionLocalProvider(LocalContentColor provides Color.White) {
        IconButton(
            onClick = onclick,
            modifier = Modifier
                .padding(vertical = 10.dp)
                .clip(CircleShape)
                .background(Color.Black.copy(0.7F))
        ) {
            Icon(imageVector = icon, contentDescription = contentDescription)
        }
    }
}

@Composable
fun LiveChatArea(
    modifier: Modifier = Modifier,
    channelId: Long
) {
    val listState = rememberLazyListState()

    val liveChatModel: LiveChatModel = hiltViewModel()
    val liveChatState = remember {
        mutableStateListOf<LiveChat>()
    }
    val chatChannel = remember {
        liveChatModel.liveChat(channelId)
    }

    LaunchedEffect(listState) {
        for (it in chatChannel) {
            liveChatState.add(it)
            listState.animateScrollToItem(liveChatState.size)
        }
    }

    DisposableEffect(Unit) {
        onDispose {
            liveChatModel.closeChannel()
        }
    }

    LazyColumn(
        state = listState,
        modifier = modifier
            .heightIn(max = 200.dp)
            .graphicsLayer { alpha = 0.99f }
            .drawWithContent {
                drawContent()

                drawRect(
                    brush = Brush.verticalGradient(
                        colorStops = arrayOf(
                            0f to Color.Transparent,
                            0.3f to Color.Black
                        )
                    ),
                    blendMode = BlendMode.DstIn
                )
            }
    ) {
        items(liveChatState.size) { index ->
            val liveChat = liveChatState[index]

            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .padding(vertical = 2.dp)
                    .clip(RoundedCornerShape(16.dp))
                    .background(Color.Black.copy(0.5F))
                    .padding(vertical = 1.5.dp, horizontal = 10.dp)
            ) {

                when (liveChat.type) {
                    MessageType.SYSTEM_MESSAGE -> {
                        // 系统消息
                        SmallText(
                            text = liveChat.content,
                            color = Color(0xFF0094D1)
                        )
                    }
                    MessageType.GROUP_MESSAGE -> {
                        // 用户消息
                        SmallText(
                            text = "${liveChat.nickname}: ",
                            color = Color(0xFF0094D1)
                        )

                        SmallText(
                            text = liveChat.content,
                            color = Color(0xFFCCCCCC)
                        )
                    }

                    else -> {}
                }
            }
        }
    }
}

@Composable
fun Streamer(
    data: Live,
    onFollow: () -> Unit = {}
) {
    val height = 64.dp
    val color = MaterialTheme.colors.surface
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .drawWithContent {
                drawContent()
                drawRect(
                    color = color.copy(alpha = 0.3F),
                    size = Size(width = size.width, height = 1.dp.toPx()),
                    topLeft = Offset(x = 0F, y = size.height - 1.dp.toPx())
                )
            }
            .padding(vertical = UIValue.VERTICAL_PADDING)
            .fillMaxWidth()
            .height(height)
    ) {
        CustomImage(
            url = data.avatar,
            contentDescription = "Avatar",
            shape = CircleShape,
            modifier = Modifier.size(height)
        )

        Spacer(modifier = Modifier.width(10.dp))

        Column(
            verticalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .fillMaxHeight()
                .weight(1F)
                .padding(vertical = UIValue.VERTICAL_PADDING)
        ) {
            SmallTitle(text = data.nickname)

            SmallAdditionalText(text = data.liveDesc)
        }

        Spacer(modifier = Modifier.width(10.dp))

        Button(
            onClick = { /*TODO*/ },
            shape = RoundedCornerShape(50)
        ) {
            SmallText(text = "关注")
        }
    }
}